package com.py.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.py.common.exception.CustomException;
import com.py.model.common.dtos.ResponseResult;
import com.py.model.common.enums.AppHttpCodeEnum;
import com.py.model.user.dtos.LoginDtao;
import com.py.model.user.pojos.ApUser;
import com.py.user.mapper.ApUserMapper;
import com.py.user.service.ApUserService;
import com.py.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description TODO
 * @Author bo.li
 * @Date 2022/11/7 14:43
 * @Version 1.0
 */
@Service
@Slf4j
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {


    @Autowired
    private ApUserService apUserService;



    @Override
    public ResponseResult login(LoginDtao loginDtao) {

        if(!StringUtils.isEmpty(loginDtao.getPhone()) && !StringUtils.isEmpty(loginDtao.getPassword())){
            //查询：根据电话
            ApUser apUser = getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, loginDtao.getPhone()));
            //判断用户是否存在
            if(apUser == null){
                throw new CustomException(AppHttpCodeEnum.LOGIN_ERROR);
            }
            //校验密码
            String srcPassword = DigestUtils.md5DigestAsHex((loginDtao.getPassword() + apUser.getSalt()).getBytes());
            if(!srcPassword.equals(apUser.getPassword())){
                throw new CustomException(AppHttpCodeEnum.LOGIN_ERROR);
            }
            //封装返回参数
            String token = AppJwtUtil.getToken(apUser.getId().longValue());
            Map<String,Object> map = new HashMap<>();
            map.put("token",token);
            map.put("user",apUser);
            return ResponseResult.okResult(map);
        } else {
            String token = AppJwtUtil.getToken(0L);
            Map<String,Object> map = new HashMap<>();
            map.put("token",token);
            return ResponseResult.okResult(map);
        }

    }


}